# 应用程序名称
APP_NAME := knife4g-server

# 源代码入口
SRC := main.go

# 版本信息，可以通过git获取或手动指定
VERSION := $(shell git describe --abbrev=0 --tags 2>/dev/null || echo "v0.3.1")
BUILD_TIME := $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
COMMIT_HASH := $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")

# 构建标志
LDFLAGS := -ldflags "\
    -X main.version=$(VERSION) \
    -X main.buildTime=$(BUILD_TIME) \
    -X main.commitHash=$(COMMIT_HASH) \
"

# 定义要构建的目标平台
PLATFORMS := \
    darwin/amd64 \
    darwin/arm64 \
    linux/amd64 \
    linux/arm64 \
    linux/386 \
    linux/arm \
    windows/amd64 \
    windows/arm64 \
    windows/386

# 默认目标
.DEFAULT_GOAL := build

# 本地构建
build:
	@echo "Building for local system..."
	go build $(LDFLAGS) -o bin/$(APP_NAME) $(SRC)

# 构建所有平台
all: clean
	@$(foreach platform, $(PLATFORMS), \
		$(call build_platform, $(platform)))

# 构建单个平台的函数
define build_platform
	OS=$(shell echo $(1) | cut -d'/' -f1); \
	ARCH=$(shell echo $(1) | cut -d'/' -f2); \
	BIN_NAME=$(APP_NAME)-$$OS-$$ARCH; \
	if [ $$OS = "windows" ]; then BIN_NAME=$$BIN_NAME.exe; fi; \
	echo "Building $$BIN_NAME..."; \
	GOOS=$$OS GOARCH=$$ARCH go build $(LDFLAGS) -o bin/$$BIN_NAME $(SRC);
endef

# 清理构建产物
clean:
	@echo "Cleaning build directory..."
	rm -rf bin/
	mkdir -p bin/

# 运行本地构建的程序
run: build
	@bin/$(APP_NAME)

# 更新依赖
tidy:
	@echo "Running go mod tidy..."
	go mod tidy

# 显示帮助信息
help:
	@echo "Available commands:"
	@echo "  make           - 构建本地系统的程序"
	@echo "  make all       - 构建所有支持的平台"
	@echo "  make clean     - 清理构建产物"
	@echo "  make run       - 构建并运行本地程序"
	@echo "  make tidy      - 更新依赖"
	@echo "  make help      - 显示帮助信息"
